package com.ruoyi.develop.goodsReimbursementDetail.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsFee.domain.GoodsFee;
import com.ruoyi.develop.goodsFee.service.IGoodsFeeService;
import com.ruoyi.develop.goodsFee.service.impl.GoodsFeeServiceImpl;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.mapper.GoodsOrderInMapper;
import com.ruoyi.develop.goodsReimbursement.domain.GoodsReimbursement;
import com.ruoyi.develop.goodsReimbursement.service.IGoodsReimbursementService;
import com.ruoyi.export.service.IExportService;
import com.ruoyi.export.service.impl.ExportServiceImpl;
import fr.opensagres.xdocreport.document.IXDocReport;
import fr.opensagres.xdocreport.document.registry.XDocReportRegistry;
import fr.opensagres.xdocreport.template.IContext;
import fr.opensagres.xdocreport.template.TemplateEngineKind;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsReimbursementDetail.domain.GoodsReimbursementDetail;
import com.ruoyi.develop.goodsReimbursementDetail.service.IGoodsReimbursementDetailService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.servlet.ModelAndView;

/**
 * 发放打款明细信息管理Controller
 * @author qh
 * @date 2023-01-16
 */
@RestController
@RequestMapping("/goodsReimbursementDetail/goodsReimbursementDetail")
public class GoodsReimbursementDetailController extends BaseController {
    @Autowired
    private IGoodsReimbursementDetailService goodsReimbursementDetailService;
    @Autowired
    private IGoodsReimbursementService goodsReimbursementService;
    @Autowired
    private ExportServiceImpl exportService;
    @Resource
    private GoodsOrderInMapper goodsOrderInMapper;
    @Resource
    private IGoodsFeeService feeService;

    @Value(value="${ruoyi.path}")
    public String basePath;

    @Value(value="${ruoyi.templatePath}")
    public String templatePath;

    @Value(value="${ruoyi.templateExport}")
    public String templateExport;

    @Value(value="${ruoyi.templateImport}")
    public String templateImport;

    @Value(value="${ruoyi.templateTmpl}")
    public String templateTmpl;

    @Value(value="${ruoyi.uploadPath}")
    public String uploadPath;
    /**
     * 查询发放打款明细信息管理列表
     */
//    @PreAuthorize("@ss.hasPermi('develop:GoodsReimbursementDetail:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsReimbursementDetail entity) {
        startPage();
        List<GoodsReimbursementDetail> list = goodsReimbursementDetailService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 导出发放打款明细信息管理列表
     */
    /*@PreAuthorize("@ss.hasPermi('develop:GoodsReimbursementDetail:export')")
    @Log(title = "发放打款明细信息管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, GoodsReimbursementDetail entity) {
        List<GoodsReimbursementDetail> list = goodsReimbursementDetailService.selectList(entity);
        ExcelUtil<GoodsReimbursementDetail> util = new ExcelUtil<GoodsReimbursementDetail>(GoodsReimbursementDetail. class);
        util.exportExcel(response, list, "发放打款明细信息管理数据");
    }*/
    @Log(title = "导出发放打款明细信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(GoodsReimbursement entity, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = new HashMap<>();

        String date = DateUtils.getTime();//默认当天
        GoodsReimbursementDetail goodsReimbursementDetail=new GoodsReimbursementDetail();
        goodsReimbursementDetail.setReimburseId(entity.getId());
        List<GoodsReimbursementDetail> list = goodsReimbursementDetailService.selectList(goodsReimbursementDetail);
        list.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("grantDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getGrantDate()));
            e.setParams(map);
        });
        GoodsOrderIn goodsOrderIn=new GoodsOrderIn();
        goodsOrderIn.setImburseId(entity.getId());
        List<GoodsOrderIn> listOrder=goodsOrderInMapper.selectBrandsList(goodsOrderIn);
        listOrder.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("buyDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getBuyDate()));
            map.put("buyYype", DictUtils.getDictLabel(BusinessConstants.BUYTYPE, e.getBuyType()));
            e.setParams(map);
        });
        params.put("listMain", entity);
        params.put("mainDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getImburseDate()));
        params.put("type", DictUtils.getDictLabel(BusinessConstants.TYPE, entity.getType()));
        params.put("status", DictUtils.getDictLabel(BusinessConstants.STATUS, entity.getStatus()));
        params.put("list", list);
        params.put("listOrder", listOrder);
        params.put("date", date);

        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "goodsReimbursement1.docx";
        }
        String templateName = "goodsReimbursement.docx";
        exportService.baseDocxExport(fileName,params,templateName,request,response);

        // exportService.convertDocx(fileName,params,templateName);
        return null;
    }

    @GetMapping("/exportExcel")
    public AjaxResult exportExcel(String id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        startPage();
        GoodsReimbursement goodsReimbursement=goodsReimbursementService.selectById(id);
        GoodsReimbursementDetail goodsReimbursementDetail=new GoodsReimbursementDetail();
        goodsReimbursementDetail.setReimburseId(id);
        List<GoodsReimbursementDetail> goodsReimbursementDetailList=goodsReimbursementDetailService.selectList(goodsReimbursementDetail);
        goodsReimbursementDetailList.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("grantDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getGrantDate()));
            /*map.put("contractDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getContractDate()));
            map.put("retentionDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getRetentionDate()));
            map.put("checkDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getCheckDate()));
            map.put("invoice", DictUtils.getDictLabel(BusinessConstants.YES_NO, e.getTaxStatus()));
            map.put("fundCallback", DictUtils.getDictLabel(BusinessConstants.FUND_CALLBACK, e.getFundCallback()));
            map.put("checkState", DictUtils.getDictLabel(BusinessConstants.YES_NO, e.getCheckState()));*/
            e.setParams(map);
        });
        GoodsOrderIn orderParams = new GoodsOrderIn();
        orderParams.setImburseId(id);
        List<GoodsOrderIn> orders = goodsOrderInMapper.selectList(orderParams);
        orders.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("buyDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getBuyDate()));
            e.setParams(map);
        });
        params.put("orders", orders);
        params.put("entity", goodsReimbursement);
        params.put("type",  DictUtils.getDictLabel(BusinessConstants.BUYTYPE, goodsReimbursement.getType()));
        params.put("status",  DictUtils.getDictLabel(BusinessConstants.STATUS, goodsReimbursement.getStatus()));
        params.put("imburseDate",  DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, goodsReimbursement.getImburseDate()));
        params.put("list", goodsReimbursementDetailList);
        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "报销详细信息.xlsx";
        }
        String templateName ="报销详细记录.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }


   /* @GetMapping("/export")
    public ModelAndView downCz(GoodsReimbursement entity,HttpServletRequest request,HttpServletResponse response) throws Exception {
        Map<String, Object> params = new HashMap<>();
        response.setHeader("Access-Control-Expose-Headers", "fileName");
        String codedFileName ="11.docx";
        InputStream in = null;
        try {
            String templateName = "goodsReimbursement.docx";
            in = new FileInputStream(basePath + File.separator + templatePath
                    + File.separator + templateExport + File.separator + templateName);
            //in = new FileInputStream(exportTemplatePath + "操作手册.docx");
            if (!this.isIE(request)) {
                codedFileName = URLEncoder.encode(codedFileName, "UTF8");
            } else {
                codedFileName = new String(codedFileName.getBytes("UTF-8"), "ISO-8859-1");
            }

            String date = DateUtils.getTime();//默认当天
            GoodsReimbursementDetail goodsReimbursementDetail=new GoodsReimbursementDetail();
            goodsReimbursementDetail.setReimburseId(entity.getId());
            List<GoodsReimbursementDetail> list = goodsReimbursementDetailService.selectList(goodsReimbursementDetail);
            list.stream().forEach(e->{
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("grantDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getGrantDate()));
                e.setParams(map);
            });
            GoodsOrderIn goodsOrderIn=new GoodsOrderIn();
            goodsOrderIn.setImburseId(entity.getId());
            List<GoodsOrderIn> listOrder=goodsOrderInMapper.selectBrandsList(goodsOrderIn);
            listOrder.stream().forEach(e->{
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("buyDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, e.getBuyDate()));
                map.put("buyYype", DictUtils.getDictLabel(BusinessConstants.BUYTYPE, e.getBuyType()));
                e.setParams(map);
            });
            params.put("listMain", entity);
            params.put("mainDate", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entity.getImburseDate()));
            params.put("type", DictUtils.getDictLabel(BusinessConstants.TYPE, entity.getType()));
            params.put("status", DictUtils.getDictLabel(BusinessConstants.STATUS, entity.getStatus()));
            params.put("list", list);
            params.put("listOrder", listOrder);
            params.put("date", date);

            response.setHeader("content-disposition", "attachment;filename=" + codedFileName);
            response.setHeader("fileName", codedFileName);
            IXDocReport report = XDocReportRegistry.getRegistry().loadReport(in, TemplateEngineKind.Velocity);
            IContext context = report.createContext();
            context.putMap(params);
            report.process(context, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return null;
    }*/
    protected boolean isIE(HttpServletRequest request) {
        return request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0 || request.getHeader("USER-AGENT").toLowerCase().indexOf("rv:11.0") > 0;
    }
    /**
     * 获取发放打款明细信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsReimbursementDetail:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsReimbursementDetailService.selectById(id));
    }

    /**
     * 新增发放打款明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsReimbursementDetail:add')")
    @Log(title = "发放打款明细信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsReimbursementDetail entity) {

        return goodsReimbursementDetailService.insert(entity);
    }

    /**
     * 修改发放打款明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsReimbursementDetail:edit')")
    @Log(title = "发放打款明细信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsReimbursementDetail entity) {
        return toAjax(goodsReimbursementDetailService.update(entity));
    }

    /**
     * 删除发放打款明细信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsReimbursementDetail:remove')")
    @Log(title = "发放打款明细信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
      goodsReimbursementDetailService.deleteByIds(ids);
        for(String id:ids){

            GoodsReimbursementDetail imburseDetail = goodsReimbursementDetailService.selectById(id);
            if(imburseDetail!=null) {
                GoodsReimbursementDetail imburseDetailParam = new GoodsReimbursementDetail();
                imburseDetailParam.setReimburseId(imburseDetail.getReimburseId());
                //计算删除某个报销发放记录之后的总报销发放金额
                List<GoodsReimbursementDetail> imburseDetailList = goodsReimbursementDetailService.selectList(imburseDetailParam);
                BigDecimal allMoney = BigDecimal.ZERO;
                for(GoodsReimbursementDetail imburseDetailEntity : imburseDetailList){
                    if (imburseDetailEntity.getGrantMoney() != null) {
                        allMoney = imburseDetailEntity.getGrantMoney().add(allMoney);
                    }
                }
                //获取报销申请信息,并与报销发放总金额对比
                GoodsReimbursement imburseMent = goodsReimbursementService.selectById(imburseDetail.getReimburseId());
                imburseMent.setRemMoney(allMoney);
                imburseMent.setRemRemain(imburseMent.getImburseMoney().subtract(allMoney));
                if(imburseMent.getRemRemain().compareTo(BigDecimal.ZERO) == 0){//剩余报销金额为0,则报销完成
                    imburseMent.setStatus("2");
                }else{
                    imburseMent.setStatus("1");
                    GoodsFee feeParam = new GoodsFee();
                    feeParam.setImburseId(imburseMent.getId());
                    GoodsOrderIn orderInParam = new GoodsOrderIn();
                    orderInParam.setImburseId(imburseMent.getId());
                    if(imburseMent.getRemRemain().compareTo(imburseMent.getImburseMoney()) == 0){//报销金额和剩余金额相等
                        // 采购 / 费用未核销
                        feeParam.setStatus("whx");
                        orderInParam.setReimburse("0");
                    }else{// 采购 / 费用部分核销
                        feeParam.setStatus("bfhx");
                        orderInParam.setReimburse("0");
                    }
                    goodsOrderInMapper.updateReimburseStatusByImburseId(orderInParam);
                    feeService.updateFeeStatusByImburseId(feeParam);
                }
                goodsReimbursementService.update(imburseMent);
            }

        }
        return null;
    }


    @GetMapping("/exportFksqd")
    public AjaxResult exportFksqd(String id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        startPage();
        GoodsReimbursement goodsReimbursement=goodsReimbursementService.selectById(id);
        params.put("entity", goodsReimbursement);
        params.put("type",  DictUtils.getDictLabel(BusinessConstants.BUYTYPE, goodsReimbursement.getType()));
        params.put("status",  DictUtils.getDictLabel(BusinessConstants.STATUS, goodsReimbursement.getStatus()));
        params.put("newDate",  DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()));
        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "付款申请单.xlsx";
        }
        String templateName ="付款申请单.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }
}
